package com.kevin.framework.http;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import android.os.AsyncTask;

import com.google.gson.Gson;
import com.kevin.framework.util.HttpUtil;
import com.kevin.framework.util.LogUtil;

/**
 * 抽象  异步任务 Get请求
 * 
 * @author tianshaokai
 * 
 * @param <Params>
 *            参数
 * @param <Progress>
 * @param <Result>
 *            结果集
 */
public abstract class AbstractGetAsyncTask<Params, Progress, Result> extends
		AsyncTask<Params, Progress, Result> {
	
	private static final String TAG = "AbstractGetAsyncTask";
	
	private HttpUtil mHttpUtil;
	private AsyncTaskCallBack mAsyncTaskCallBack;
	private Class<Result> result;
	private Gson gson;

	public AbstractGetAsyncTask(Class<Result> result,
			AsyncTaskCallBack mAsyncTaskCallBack) {
		this.mAsyncTaskCallBack = mAsyncTaskCallBack;
		this.result = result;
		this.gson = new Gson();
		this.mHttpUtil = new HttpUtil();
	}

	@Override
	protected Result doInBackground(Params... params) {
		InputStream inputstream = mHttpUtil.sendHttpClientGetRequest(getRequestUrl(params));
		return parse(inputstream, result);
	}
	
	private Result parse(InputStream is, Class<Result> t) {
		Result t1 = null;
		try {
			Reader reader = new InputStreamReader(new BufferedInputStream(is));
			t1 = gson.fromJson(reader, t);
			return t1;
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(TAG, "Failed to parse json. error: " + e.toString());
		} finally {
			try { 
				if (is != null) {
					is.close();
				} 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return t1;
	}
	
	@Override
	protected void onPostExecute(Result result) {
		super.onPostExecute(result);
		
		mAsyncTaskCallBack.onPostExecute(result);
	}
	
	public abstract String getRequestUrl(Params... params);

}
